package com.snowyee.snowyeecodesandbox.controller;


import com.snowyee.snowyeecodesandbox.model.ExecuteCodeRequest;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeResponse;
import com.snowyee.snowyeecodesandbox.service.impl.DockerCodeSandboxImpl;
import com.snowyee.snowyeecodesandbox.service.impl.DockerCodeSandboxImplOld;
import com.snowyee.snowyeecodesandbox.service.impl.JavaCodeSandboxImplOld;
import com.snowyee.snowyeecodesandbox.service.impl.JavaCodeSandboxmpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {
    // 定义鉴权请求头和密钥
    // 一般在公司内API服务使用
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaCodeSandboxmpl javaCodeSandboxmpl;

    @Resource
    private JavaCodeSandboxImplOld javaCodeSandboxImplOld;

    @Resource
    private DockerCodeSandboxImplOld dockerCodeSandboxImplOld;

    @Resource
    private DockerCodeSandboxImpl dockerCodeSandboxImpl;

    @GetMapping("/health")
    public String healthCheck()
    {
        return "ok";
    }

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
        // 判断调用接口者是否有权限
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!authHeader.equals(AUTH_REQUEST_SECRET)){
            response.setStatus(403);
            return null;
        }

        if (executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        return javaCodeSandboxmpl.executeCode(executeCodeRequest);
    }
}


